import BaseModel from './BaseModel'
import { post } from '@/api/ajax'
import {EnumApi} from '@/api/apis'
import { EnumType } from './types'
import AccountModel from './AccountModel'
import ArticleModel from './ArticleModel'
import { EnumType as EnumItemType } from '@/components/global/enum/types'

class EnumModel extends BaseModel implements EnumItemType {

  // 名称
  public name = ''
  // 索引
  public index = '0'
  // 类型
  public type = ''
  // 路径
  public path = ''
  // 描述
  public description = ''
  // 子对象
  public children = []
  // 创建人
  public createUser: AccountModel | string = ''
  // 层次
  public tier = 0
  // 父类ID
  public superId = ''
  // UUID
  public uuid = ''
  // 项目ID
  public project: ArticleModel | string = ''
  // 数据说明
  public dataShow = ''

  // 删除数据的API
  removeDataApi = EnumApi.remoce
  // 详情的API
  detailApi = EnumApi.detail

  get isFile() {
    return this.type === EnumType.FILE
  }

  get typeText() {
    return this.type === EnumType.FILE ? '文件' : '文件夹'
  }

  get enumPath() {
    let indexStr = this._id
    if (this.path.includes('/:id')) {
      indexStr = this.path.replace(':id', indexStr)
    }
    return indexStr
  }

  setDataWithJson(json: {}) {
    super.setDataWithJson(json);
    this.children = EnumModel.getModelsWithArr(this.children)
    EnumModel.setSuperId(this._id, this.children)
    this.index = `${this.index}`
    if (this.createUser) {
      this.createUser = AccountModel.create<AccountModel>(this.createUser)
    }
    if (this.project) {
      this.project = ArticleModel.create<ArticleModel>(this.project)
    }
  }

  static setSuperId(superId: string, arr: Array<EnumModel>) {
    arr.forEach((item) => {
      item.superId = superId
    })
  }

  /**
   * 更新项目
   */
  update() {
    let keys = 'name index type description'
    if (this.type === EnumType.FILE) {
      keys = `${keys} uuid path`
    }
    return post(`${EnumApi.update}/${this._id}`, this.getJson(keys))
  }

  removeData(msg: string): Promise<unknown> {
    return super.removeData(msg, {
      superId: this.superId
    });
  }

  /**
   * 创建
   */
  create(isProject = true) {
    let keys = 'project superId name type index description'
    if (this.type === EnumType.FILE) {
      keys = `${keys} uuid path`
    }
    return post(EnumApi.create, this.getJson(keys, { isProject }))
  }

  updataDataShow() {
    return post(`${EnumApi.updataDataShow}/${this._id}`, {
      dataShow: this.dataShow
    })
  }
}

export default EnumModel
